package top.fongs.spring_security_jwt.configure.web_security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import top.fongs.spring_security_jwt.service.inter.users.user_detail.UserDetailService;
import top.fongs.spring_security_jwt.web.filters.once_per_request.AppOncePerRequestFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity( prePostEnabled = true )
public class WebSecurityConfigure extends WebSecurityConfigurerAdapter {

    private final UserDetailService userDetailService;

    @Autowired
    public WebSecurityConfigure( UserDetailService userDetailService ) {
        this.userDetailService = userDetailService;
    }


    @Override
    protected void configure( AuthenticationManagerBuilder auth ) throws Exception {
        auth.userDetailsService( userDetailService );
    }

    @Override
    protected void configure( HttpSecurity http ) throws Exception {
        http
                // 关闭跨域伪装保护
                .csrf( ).disable( )
                // 使用json web token 关闭session
                .sessionManagement( ).sessionCreationPolicy( SessionCreationPolicy.STATELESS )
                .and( )
                .authorizeRequests( )
                // 允许对于网站静态资源的无授权访问
                .antMatchers( HttpMethod.GET,
                        "/", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js" ).permitAll( )
                // 对于获取token的rest api要允许匿名访问
                .antMatchers( "/sign-in", "/sign-up", "/re-sign-in" ).permitAll( )
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest( ).authenticated( )
                .and( )
                // 注入filter
                .addFilterBefore( new AppOncePerRequestFilter( ), UsernamePasswordAuthenticationFilter.class )
                /*.addFilter( new AuthorizationFilter( authenticationManager( ) ) )
                .addFilter( new AuthenticationFilter( authenticationManager( ) ) )*/
                // 禁用缓存
                .headers( ).cacheControl( );
    }

}
